package com.wh.springbootshiromanyrealm.modularauthenticate;

import com.wh.springbootshiromanyrealm.token.MyToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @Auther: HuiEr
 * @Date: 2020/3/4 21:24
 * @Description
 */
public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {

        this.assertRealmsConfigured();
        MyToken myToken=(MyToken)authenticationToken;
        String loginType = myToken.getLoginType();
        Collection<Realm> realms = getRealms();
        Collection<Realm> typeRealm = new ArrayList<>();
        for(Realm realm:realms){
            if (realm.getName().contains(loginType)){
                    typeRealm.add(realm);
            }
        }
        /*return typeRealm.size() ==1?doSingleRealmAuthentication(typeRealm.iterator().next(),authenticationToken):
                doMultiRealmAuthentication(typeRealm,authenticationToken);*/

        if(typeRealm.size()==1){
            return doSingleRealmAuthentication(typeRealm.iterator().next(),myToken);
        }else{
            return doMultiRealmAuthentication(typeRealm,myToken);
        }
    }
}
